import axios from "axios";

const auth = {
    isLogin() {
        return this.getToken();
    },
    tokenKey: "AUTH_TOKEN",
    refreshTokenKey: "REFRESH_TOKEN",
    userInfoKey: "USER_INFO",
    userDetail: "USER_DETAIL",
    getItem(key) {
        try {
            return JSON.parse(localStorage.getItem(key));
        } catch (e) {
            return false;
        }
    },
    getToken() {
        return this.getItem(this.tokenKey);
    },
    getRefreshToken() {
        return this.getItem(this.refreshTokenKey);
    },
    getUserInfo() {
        return this.getItem(this.userInfoKey);
    },
    getUserDetail() {
        return this.getItem(this.userDetail);
    },
    validPrivCode(code) {
        if (!code) {
            return true;
        }
        let data = this.getUserInfo();
        if (data && data.length) {
            return data.indexOf(code) > -1;
        } else {
            return false;
        }
    },
    addRouterEach(router) {
        const _vm = this;
        router.beforeEach((to, from, next) => {
            /* 当前路由所有人可见 */
            if (to.meta && to.meta.anonymous === true) {
                next();
            } else if (_vm.isLogin()) {
                if (
                    to.meta &&
                    to.meta.privCode &&
                    _vm.validPrivCode(to.meta.privCode) === false
                ) {
                    /* 路由需要校验权限，权限不足 */
                    next({ path: "/nopriv" });
                } else {
                    /* 路由需要校验权限，且校验通过 */
                    next();
                }
            } else {
                auth.removeToken();
                window.location.href = process.env.VUE_APP_RELOAD;
            }
        });
    },
    saveItem(key, data) {
        localStorage.setItem(key, JSON.stringify(data));
    },
    saveToken(data) {
        this.saveItem(this.tokenKey, data);
    },
    saveRefreshToken(data) {
        this.saveItem(this.refreshTokenKey, data);
    },
    saveUserInfo(data) {
        this.saveItem(this.userInfoKey, data);
    },
    saveUserDetail(data) {
        this.saveItem(this.userDetail, data);
    },
    removeToken() {
        localStorage.clear();
    },
    removeItem(key) {
        localStorage.removeItem(key);
    },
};
const VueAuth = {
    install(Vue) {
        Vue.prototype.$auth = auth;
    },
};

export { VueAuth, auth };
